<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\UserVideoCollection;
use app\common\model\VideoAnalyzeService;

class Video
{

    /**
     * 详情
     * @param $param
     * @return array
     */
    public function getInfo($param): array
    {
        // 提取参数
        $id = $param['id'];
        $userId = $param['userId'];
        $appId = getAppId();

        // 查询条件
        $where = [['a.id', '=', $id], ['a.status', '=', 1]];

        // 查询数据
        $info = app(\app\common\model\Video::class)
            ->alias('a')
            ->where($where)
            ->find();
        $info = $info->toArray();
        if (!$info) {
            throw new BusinessException('视频信息不存在');
        }

        // 检查是否开通视频合集
        if ($info['is_free'] != 1) {
            $collection = app(UserVideoCollection::class)->getUserValidVideoCollection($userId, $info['collection_id']);
            if (!$collection) {
                throw new BusinessException('您未开通该视频合集');
            }
        }

        // 根据启用插件生成视频地址
        $analyze_service = $info['analyze_service'];
        if (!empty($analyze_service)) {

            // 根据服务编号查询服务名称
            $service_name = app(VideoAnalyzeService::class)
                ->where([['id', '=', $analyze_service]])
                ->value('service', '');
            if (!$service_name) {
                throw new BusinessException('视频解析服务不存在');
            }

            // 初始化service
            $service = app($service_name, [], true);
            $service->init($appId);

            // 视频地址签名
            $info['url'] = $service->buildSignedUrl($info['url'], 3600);

            // 更新视频地址
            app(\app\common\model\Video::class)->where(['id'=>$id])->update(['url' => $info['url']]);
        }

        // 返回
        return $info;
    }

}